package com.sssre.business.service.impl;
import java.util.Date;

import com.sssre.business.domain.BusBpmnInfo;
import com.sssre.business.domain.BusCarPackageAudit;
import com.sssre.business.domain.BusServiceItem;
import com.sssre.business.exception.ServiceValidException;
import com.sssre.business.mapper.BusCarPackageAuditMapper;
import com.sssre.business.mapper.BusServiceItemMapper;
import com.sssre.business.service.IBusBpmnInfoService;
import com.sssre.business.service.IBusServiceItemService;
import com.sssre.business.vo.AuditInfoVO;
import com.sssre.business.vo.AuditVO;
import com.sssre.common.core.domain.entity.SysUser;
import com.sssre.common.utils.DateUtils;
import com.sssre.common.utils.SecurityUtils;
import com.sssre.system.mapper.SysUserMapper;
import com.sssre.system.service.ISysConfigService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * 服务项Service业务层处理
 *
 * @author 浪兎兎
 * @date 2025-04-28
 */
@Service
public class BusServiceItemServiceImpl implements IBusServiceItemService {
    @Autowired
    private BusServiceItemMapper busServiceItemMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBusBpmnInfoService busBpmnInfoService;
    @Autowired
    private BusCarPackageAuditMapper busCarPackageAuditMapper;

    /**
     * 查询服务项
     *
     * @param id 服务项主键
     * @return 服务项
     */
    @Override
    public BusServiceItem selectBusServiceItemById(Long id) {
        return busServiceItemMapper.selectBusServiceItemById(id);
    }

    /**
     * 查询服务项列表
     *
     * @param busServiceItem 服务项
     * @return 服务项
     */
    @Override
    public List<BusServiceItem> selectBusServiceItemList(BusServiceItem busServiceItem) {
        return busServiceItemMapper.selectBusServiceItemList(busServiceItem);
    }

    /**
     * 新增服务项
     *
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int insertBusServiceItem(BusServiceItem busServiceItem) {
        // 判断是否套餐
        if (busServiceItem.getCarPackage().equals(BusServiceItem.NO)) {
            // 设置无需审核
            busServiceItem.setAuditStatus(BusServiceItem.WHTHOUT_AUDIT_STATUS);
        } else {
            // 设置审核状态初始化
            busServiceItem.setAuditStatus(BusServiceItem.AUDIT_STATUS_INIT);
        }
        // 价格合理化校验
        if (!busServiceItem.getOriginalPrice().max(busServiceItem.getDiscountPrice()).equals(busServiceItem.getOriginalPrice())) {
            throw new ServiceValidException("折扣价不能大于原价");
        }
        if (busServiceItem.getOriginalPrice().intValue() <= 0 || busServiceItem.getDiscountPrice().intValue() < 0) {
            throw new ServiceValidException("价格必须大于0");
        }
        // 设置上架状态为未上架
        busServiceItem.setSaleStatus(BusServiceItem.NO);
        // 设置创建时间
        busServiceItem.setCreateTime(DateUtils.getNowDate());
        // 提交数据
        return busServiceItemMapper.insertBusServiceItem(busServiceItem);
    }

    /**
     * 修改服务项
     *
     * @param busServiceItem 服务项
     * @return 结果
     */
    @Override
    public int updateBusServiceItem(BusServiceItem busServiceItem) {
        // 检测审核状态初始化
        // 检测上架状态为未上架
        BusServiceItem old = busServiceItemMapper.selectBusServiceItemById(busServiceItem.getId());
        System.err.println(old);
        if (BusServiceItem.YES.equals(old.getSaleStatus())
                || BusServiceItem.AUDIT_STATUS_PERFORM.equals(old.getAuditStatus())) {
            throw new ServiceValidException("只有未提交审核且未上架的服务才可以被修改");
        }
        // 价格合理化校验
        if (busServiceItem.getOriginalPrice().intValue() <= 0 || busServiceItem.getDiscountPrice().intValue() < 0) {
            throw new ServiceValidException("价格必须大于0");
        }
        if (!busServiceItem.getOriginalPrice().max(busServiceItem.getDiscountPrice()).equals(busServiceItem.getOriginalPrice())) {
            throw new ServiceValidException("折扣价不能大于原价");
        }
        // 判断是否套餐
        if (busServiceItem.getCarPackage().equals(BusServiceItem.NO)) {
            // 设置无需审核
            busServiceItem.setAuditStatus(BusServiceItem.WHTHOUT_AUDIT_STATUS);
        } else {
            // 设置审核状态初始化
            busServiceItem.setAuditStatus(BusServiceItem.AUDIT_STATUS_INIT);
        }
        return busServiceItemMapper.updateBusServiceItem(busServiceItem);
    }

    /**
     * 批量删除服务项
     *
     * @param ids 需要删除的服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            throw new ServiceValidException("数据不能为空");
        }
        for (Long id : ids) {
            // 查询原始对象
            deleteValid(id);
        }
        return busServiceItemMapper.deleteBusServiceItemByIds(ids);
    }

    /**
     * 删除服务项信息
     *
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int deleteBusServiceItemById(Long id) {
        if (id == null) {
            throw new RuntimeException("数据不能为空");
        }
        deleteValid(id);
        return busServiceItemMapper.deleteBusServiceItemById(id);
    }

    /**
     * 删除校验
     *
     * @param id 删除的id
     */
    private void deleteValid(Long id) {
        // 查询原始对象
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        // 判断这个对象是否上架 | 删除
        if (busServiceItem == null) {
            throw new ServiceValidException("该对象不存在");
        } else if (!busServiceItem.getSaleStatus().equals(BusServiceItem.NO)) {
            throw new ServiceValidException("必须是下架的服务才能删除");
        } else if (busServiceItem.getAuditStatus().equals(BusServiceItem.AUDIT_STATUS_PERFORM)) {
            throw new ServiceValidException("审核中的服务不能删除");
        }
    }

    /**
     * 上架服务项信息
     *
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int saleOn(Long id) {
        // 查询原始对象
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        // 判断这个对象是否下架
        if (!busServiceItem.getSaleStatus().equals(BusServiceItem.NO)) {
            throw new ServiceValidException("必须是下架的服务才能上架");
        }
        // 判断是否审核通过或无需审核
        if (!busServiceItem.getAuditStatus().equals(BusServiceItem.AUDIT_STATUS_PASS) && !busServiceItem.getAuditStatus().equals(BusServiceItem.WHTHOUT_AUDIT_STATUS)) {
            throw new ServiceValidException("你没有权限上架，因为未审核完成，或审核被拒绝");
        }
        return busServiceItemMapper.saleOn(id);
    }

    /**
     * 下架服务项信息
     *
     * @param id 服务项主键
     * @return 结果
     */
    @Override
    public int saleOff(Long id) {
        // 查询原始对象
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        // 判断这个对象是否上架
        if (!busServiceItem.getSaleStatus().equals(BusServiceItem.YES)) {
            throw new ServiceValidException("必须是上架的服务才能下架");
        }
        return busServiceItemMapper.saleOff(id);
    }

    /**
     * 获取审核信息
     *
     * @param id 主键
     * @return 结果
     */
    @Override
    public AuditInfoVO getAuditInfoVO(Long id) {
        AuditInfoVO auditInfoVO = new AuditInfoVO();
        // 参数合法性验证
        if (id == null) {
            throw new ServiceValidException("非法参数");
        }
        // 查询服务项明细
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(id);
        if (busServiceItem == null) {
            throw new ServiceValidException("该数据不存在");
        }
        auditInfoVO.setServiceItem(busServiceItem);
        // 查询店长用户列表
        List<SysUser> shopOwners = sysUserMapper.selectUserByRoleKey("shopOwner");
        auditInfoVO.setShopOwnerList(shopOwners);
        // 阈值
        String discountPriceLimitString = sysConfigService.selectConfigByKey("discountPriceLimit");
        BigDecimal discountPriceLimit = new BigDecimal(discountPriceLimitString);
        auditInfoVO.setDiscountPriceLimit(discountPriceLimit);
        if (busServiceItem.getDiscountPrice().compareTo(discountPriceLimit) > 0) {
            // 查询财务用户列表
            List<SysUser> finances = sysUserMapper.selectUserByRoleKey("finance");
            auditInfoVO.setFinanceList(finances);
        }
        return auditInfoVO;
    }

    /**
     * 发起审核
     *
     * @param auditVO 流程实例vo
     * @return 结果
     */
    @Override
    @Transactional
    public int startAudit(AuditVO auditVO) {
        // 校验参数合法性
        if (auditVO == null) {
            throw new ServiceValidException("非法参数");
        }
        // 根据服务项id查询原始对象
        Long serviceItemId = auditVO.getServiceItemId();
        BusServiceItem busServiceItem = busServiceItemMapper.selectBusServiceItemById(serviceItemId);
        if (busServiceItem == null) {
            throw new ServiceValidException("非法参数");
        }
        // 财务的校验
        String discountPriceLimitString = sysConfigService.selectConfigByKey("discountPriceLimit");
        BigDecimal discountPriceLimit = new BigDecimal(discountPriceLimitString);
        if (busServiceItem.getDiscountPrice().compareTo(discountPriceLimit) >= 0) {
            if (auditVO.getFinanceId() == null) {
                throw new ServiceValidException("财务不能为空");
            }
        }
        // 查询财务和店长
        Long shopOwnerId = auditVO.getShopOwnerId();
        Long financeId = auditVO.getFinanceId();
        SysUser shopOwner = sysUserMapper.selectUserById(shopOwnerId);
        SysUser finance = sysUserMapper.selectUserById(financeId);
        // 判断状态是否正确
        Integer auditStatus = busServiceItem.getAuditStatus();
        Integer saleStatus = busServiceItem.getSaleStatus();
        Integer carPackage = busServiceItem.getCarPackage();
        if (!auditStatus.equals(BusServiceItem.AUDIT_STATUS_INIT)) {
            throw new ServiceValidException("服务套餐必须初始化状态才能发起审核");
        } else if (!saleStatus.equals(BusServiceItem.NO) ) {
            throw new ServiceValidException("服务套餐必须下架才能发起审核");
        } else if (!carPackage.equals(BusServiceItem.YES)) {
            throw new ServiceValidException("服务套餐必须是套餐才能发起审核");
        }
        // 查询 bpmnInfo 信息
        BusBpmnInfo busBpmnInfo = busBpmnInfoService.selectBusBpmnInfoByType(BusCarPackageAudit.FLOW_AUDIT_TYPE);
        // 插入表
        BusCarPackageAudit busCarPackageAudit = new BusCarPackageAudit();
        busCarPackageAudit.setServiceItemId(serviceItemId);
        busCarPackageAudit.setServiceItemName(busServiceItem.getName());
        busCarPackageAudit.setServiceItemInfo(busServiceItem.getInfo());
        busCarPackageAudit.setServiceItemPrice(busServiceItem.getDiscountPrice());
        busCarPackageAudit.setInfo(auditVO.getInfo());
        busCarPackageAudit.setCreatorId(SecurityUtils.getUserId().toString());
        busCarPackageAudit.setStatus(BusCarPackageAudit.STATUS_IN_PROGRESS);
        busCarPackageAudit.setCreateTime(new Date());
        busCarPackageAuditMapper.insertBusCarPackageAudit(busCarPackageAudit);
        // 使用 act 生成流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(busBpmnInfo.getProcessDefinitionKey(),busCarPackageAudit.getId().toString(), new HashMap<String, Object>() {
            {
                this.put("shopOwner", shopOwner.getUserId());
                if (finance != null) {
                    this.put("finance", finance.getUserId());
                }
                this.put("price", busServiceItem.getDiscountPrice().doubleValue());
                this.put("discountPriceLimit", Double.valueOf(discountPriceLimitString));
            }
        });
        String processInstanceId = processInstance.getProcessInstanceId();
        String businessKey = processInstance.getBusinessKey();
        if (processInstanceId == null || businessKey == null) {
            throw new ServiceValidException(processInstanceId + " :: " + businessKey);
        }
        // 设置实例id
        busCarPackageAuditMapper.updateInstanceId(busCarPackageAudit.getId(), processInstanceId);
        // 服务项状态改成审核中
        return busServiceItemMapper.updateStatus(busServiceItem.getId(), BusServiceItem.AUDIT_STATUS_PERFORM);
    }
}
